package com.xiaren.util;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import com.xiaren.biz.FrameBiz;
import com.xiaren.biz.PublicFunction;
import com.xiaren.common.IConstant;
import com.xiaren.common.ImageManager;
import com.xiaren.common.ObjectConstant;

/**
 * @主页 http://www.leaf123.cn/
 * @邮箱 xia5523@qq.com
 */
public class SystemTrayUtil {

	public static SystemTray tray = null;
	public static TrayIcon trayIcon = null;

	/**
	 * 为窗体添加托盘事件
	 */
	public static void addSystemTray() {
		if (SystemTray.isSupported()) {// 判断当前平台是否支持托盘功能
			// 创建托盘实例
			tray = SystemTray.getSystemTray();
			// 创建托盘图标：1.显示图标Image 2.停留提示text 3.弹出菜单popupMenu 4.创建托盘图标实例
			// 2.停留提示text
			// 3.弹出菜单popupMenu
			PopupMenu popMenu = new PopupMenu();
			MenuItem itmOpen = new MenuItem("open");
			itmOpen.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					ObjectConstant.mainFrame.setVisible(true);
				}
			});
			MenuItem itmHide = new MenuItem("hidden");
			itmHide.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					ObjectConstant.mainFrame.setVisible(false);
				}
			});
			MenuItem itmExit = new MenuItem("exit");
			itmExit.addActionListener(new ActionListener() {
				// 用于窗体关闭时记住窗体的位置
				public void actionPerformed(ActionEvent e) {
					PublicFunction.exitSys();
				}
			});
			popMenu.add(itmOpen);
			popMenu.add(itmHide);
			popMenu.add(itmExit);

			// 创建托盘图标
			trayIcon = new TrayIcon(ImageManager.IMAGE_TITLE.getImage()
					.getScaledInstance(20, 20, Image.SCALE_DEFAULT),
					IConstant.JFRAME_TITLE, popMenu);
			trayIcon.addMouseListener(new MouseAdapter() {
				public void mousePressed(MouseEvent e) {
					if (MouseEvent.BUTTON1 == e.getButton()){
						if (ObjectConstant.mainFrame.isVisible()) {
							ObjectConstant.mainFrame.setVisible(false);
						} else {
							FrameBiz.setFrameVisible();
						}
					}
				}
			});

			// 将托盘图标加到托盘上
			try {
				tray.add(trayIcon);
			} catch (AWTException e1) {
				e1.printStackTrace();
			}

		}

//		KeyBoardMonitor monitor = KeyBoardMonitor.getInstance();
//		System.out.println("1111");
//		monitor.setSystemKBListener(new SystemKBListener() {
//			public void keyDown(int arg0) {
////				if (arg0 == KeyEvent.VK_WINDOWS)
////					System.out.println("sucesss");
//
//			}
//
//			public void keyUp(int arg0) {
//			}
//
//		});
//		
//		monitor.enableMonitor();

	}
}
